package com.lsp.java.dataStructure.array;

public class ArrayTestStruct {

    private int size;
    private int data[];
    private int index; //当前已缓存数据的大小

    public ArrayTestStruct(int size) {//数组初始化过程
        this.size = size;
        data = new int[size];//分配的内存空间
        this.index = 0;
    }

    public void print() {
        System.out.println("index:" + index);
        for (int i = 0; i < index; i++) {
            System.out.println(data[i] + " ");
        }
        System.out.println();
    }

    public void insert(int loc, int n) {//时间复杂度是 O(n)
        //在loc位置插入n
        if (index++ < size) {
            //插入数据的话，index是要加1的，判断index++和size的值
            for (int i = size - 1; i > loc; i--) {
                data[i] = data[i - 1];//把数据往后移动一个
            }
            data[loc] = n;
        } else {
            //扩容会把size *2或者*0.75
            size = size * 2;
            int temp[] = new int[size];
        }
    }

    public void delete(int loc) {
        for (int i = loc; i < size; i++) {
            if (i != size - 1) { //怕越界，所以要判断
                data[i] = data[i + 1];
            } else {
                data[i] = 0;
            }
        }
        index--;
    }

    public void update(int loc, int n) {
        data[loc] = n;
    }

    public int get(int loc) {
        return data[loc];
    }

    public static void main(String[] args) {
        ArrayTestStruct arrayTestStruct = new ArrayTestStruct(5);
        arrayTestStruct.insert(3, 4);
        arrayTestStruct.insert(1, 2);
        System.out.println(arrayTestStruct);
        System.out.println(arrayTestStruct.get(0));
        System.out.println(arrayTestStruct.get(1));
        System.out.println(arrayTestStruct.get(2));
        System.out.println(arrayTestStruct.get(3));
        System.out.println(arrayTestStruct.get(4));
    }
}
